﻿using System;
using System.Linq.Expressions;
using System.Reflection;
using MyLib.Data;

namespace MyLib.Web {
	/// <summary>
	/// 
	/// </summary>
	public abstract class MyUserControl : System.Web.UI.UserControl, IDbContext {
		/// <summary>
		/// 
		/// </summary>
		protected log4net.ILog m_logger;

		/// <summary>
		/// 
		/// </summary>
		protected MyUserControl() {
			m_logger = log4net.LogManager.GetLogger(GetType());
		}

		/// <summary>
		/// 
		/// </summary>
		private static readonly PropertyInfo m_viewStatePropertyInfo = typeof(System.Web.UI.Page)
			.GetProperty("ViewState", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

		private System.Web.UI.StateBag m_cachedPageViewState = null;

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected System.Web.UI.StateBag PageViewState {
			get {
				if (m_cachedPageViewState == null) {
					var p0 = Expression.Parameter(typeof(System.Web.UI.Page));
					var exp = Expression.Lambda<Func<System.Web.UI.Page, System.Web.UI.StateBag>>(
						Expression.Property(
							p0,
							m_viewStatePropertyInfo),
						p0).Compile();

					m_cachedPageViewState = exp(Page);
				}

				return m_cachedPageViewState;
			}
		} // end of PageViewState.

		/// <summary>
		/// 
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		protected T GetDbProvider<T>() where T : DbContextProvider, new() {
			return (T)((MyPage)Page).HttpResource.GetDbProvider(typeof(T));
		}

		/// <summary>
		/// 
		/// </summary>
		[Obsolete("Use MyPage instead")]
		SessionFactory IDbContext.SessionFactory {
			get {
				return ((IDbContext)Page).SessionFactory;
			}
		}
	} // end of MyUserControl.
}
